const Router = require('koa-router')
const router = new Router()
const request = require('../../request')
const validator = require('../../middleware/validator')
const { toObject } = require('../../../utils')

module.exports = router

router.put('/subscribe', validator({
  tagId: {
    type: 'string',
    required: true
  }
}), async (ctx, next) => {
  const { body, statusCode, headers } = await subsribe(ctx)
  ctx.status = statusCode
  ctx.set('Content-Type', headers['content-type'])
  ctx.body = body
})

router.delete('/subscribe', validator({
  tagId: {
    type: 'string',
    required: true
  }
}), async (ctx, next) => {
  const { body, statusCode, headers } = await subsribe(ctx)
  ctx.status = statusCode
  ctx.set('Content-Type', headers['content-type'])
  ctx.body = body
})

function subsribe(ctx) {
  const headers = ctx.headres
  const options = {
    url: 'https://gold-tag-ms.juejin.im/v1/tag/subscribe/' + ctx.request.body.tagId,
    method: ctx.method,
    headers: {
      'X-Juejin-Src': 'web',
      'X-Juejin-Client': headers['x-device-id'],
      'X-Juejin-Token': headers['x-token'],
      'X-Juejin-Uid': headers['x-uid'],
    }
  };
  return request(options);
}

router.get('/detail', validator({
  tagName: {
    type: 'string',
    required: true
  }
}), async (ctx, next) => {
  const headers = ctx.headers
  const options = {
    url: 'https://gold-tag-ms.juejin.im/v1/tag/' + ctx.query.tagName,
    method: "GET",
    headers: {
      'X-Juejin-Src': 'web',
      'X-Juejin-Client': headers['x-device-id'],
      'X-Juejin-Token': headers['x-token'],
      'X-Juejin-Uid': headers['x-uid'],
    }
  };
  let { body } = await request(options)
  ctx.body = body
})

router.get('/entry', validator({
  tagId: { type: 'string', required: true },
  page: {
    type: 'string',
    required: true,
    validator: (rule, value) => Number(value) > 0,
    message: 'page 需传入正整数'
  },
  pageSize: {
    type: 'string',
    required: true,
    validator: (rule, value) => Number(value) > 0,
    message: 'pageSize 需传入正整数'
  },
  sort: {
    type: 'enum',
    required: true,
    enum: ['rankIndex', 'createdAt', 'hotIndex']
  }
}), async (ctx, next) => {
  const headers = ctx.headers
  const options = {
    url: 'https://timeline-merger-ms.juejin.im/v1/get_tag_entry',
    method: "GET",
    headers: {
      'X-Juejin-Src': 'web',
      'X-Juejin-Client': headers['x-device-id'],
      'X-Juejin-Token': headers['x-token'],
      'X-Juejin-Uid': headers['x-uid'],
    },
    params: {
      src: 'web',
      uid: headers['x-uid'],
      device_id: headers['x-device-id'],
      token: headers['x-token'],
      tagId: ctx.query.tagId,
      page: ctx.query.page || 0,
      pageSize: ctx.query.pageSize || 20,
      sort: ctx.query.sort || 'rankIndex',
    }
  };
  let { body } = await request(options)
  body = toObject(body)
  ctx.body = {
    s: body.s,
    d: body.d.entrylist || []
  }
})
